/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lt.ntec.danblog.server.blog.model.objectify;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import lt.ntec.danblog.server.core.model.User;
import lt.ntec.danblog.server.core.model.UserDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Tadas
 */
class CommentUserProxy implements InvocationHandler {

    private static final Logger LOG = LoggerFactory.getLogger(CommentUserProxy.class);
    private User user;
    private final BlogComment blogComment;
    private final UserDAO userDAO;

    public static User newInstance(BlogComment blogComment, UserDAO userDAO) {
        return (User) Proxy.newProxyInstance(User.class.getClassLoader(),
                                             new Class[]{User.class},
                                             new CommentUserProxy(blogComment, userDAO));
    }

    private CommentUserProxy(BlogComment blogComment, UserDAO userDAO) {
        this.blogComment = blogComment;
        this.userDAO = userDAO;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws
            IllegalAccessException, IllegalArgumentException,
            InvocationTargetException {
        Long userId = blogComment.getUserId();
        
        if (userId == null) {
            throw new IllegalStateException(
                    "Comment should have saved authorId");
        }
        
        if (user == null) {
            LOG.debug("Creating proxy");
            user = userDAO.getById(userId);
        }

        LOG.debug("Delegating call for " + method.getName());

        return method.invoke(user, args);
    }
}
